package com.caifu.util;

import com.baidu.aip.face.AipFace;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;


/**
 * @author
 */
public class BaiduFaceUtils {
    private static final Logger logger = LoggerFactory.getLogger(BaiduFaceUtils.class);

    /**
     * 官网文档：https://ai.baidu.com/ai-doc/FACE/8k37c1rqz#%E4%BA%BA%E8%84%B8%E5%AF%B9%E6%AF%94
     * <p>
     * 银山百度人脸官方参数
     */
    public static final String BD_FACE_APP_ID = "17010974";
    public static final String GROUP_ID = "wh_1";
    public static final String BD_FACE_API_KEY = "r0vUClHG3Y3HyIbIOG2PgoBa";
    public static final String BD_FACE_SECRET_KEY = "jO4dpgx7Rffd0Yi1DrWE71TgFZa1hsTy";


    /**
     * 成功返回的code
     */
    public static final String SUCCESS_CODE = "0";
    /**
     * 该人脸已存在
     */
    public static final String FACE_EXIST_CODE = "223105";
    /**
     * 未找到匹配
     */
    public static final String USER_NOT_MATCHED_CODE = "222207";
    /**
     * 添加时 人脸已存在
     */
    public static final String FACE_ALREADY_EXIST_CODE = "223105";


    /**
     * 人脸识别
     */
    public static Map<String, Object> isFaceApiIdentify(String imgUrl) {
        Map<String, Object> result = new HashMap<>(10);
        try {
            // 活的 AipFaceClient
            AipFace client = BaiduClient.getBaiduClient();
            // 可选：设置网络连接参数
            client.setConnectionTimeoutInMillis(2000);
            client.setSocketTimeoutInMillis(60000);
            // 调用接口
            String imageType = "URL";

            HashMap<String, String> options = new HashMap<>(10);
            // 人脸检测
            JSONObject res = client.detect(imgUrl, imageType, options);
            logger.info("人脸检测res：" + res);
            String returnCode = res.get("error_code").toString();

            if (SUCCESS_CODE.equals(returnCode)) {
                result.put("code", "0");
                result.put("msg", "人脸识别通过");
                //通过后搜索人脸是否存在  存在继续追加  不存在增加
                String userId = faceSearch(imgUrl,result);
                result.put("faceUserId", userId);
            } else if (FACE_EXIST_CODE.equals(returnCode)) {
                result.put("code", res.get("error_code"));
                result.put("msg", "该人脸已存在,请不要重复添加人脸");
            } else {
                result.put("code", "99");
                result.put("msg", "人脸识别失败");
            }
            return result;
        } catch (Exception e) {
            logger.info(e.getMessage());
            e.printStackTrace();
            result.put("code", "99");
            result.put("msg", "人脸识别失败");
            return result;
        }
    }

    /**
     * 人脸搜索
     *
     * @param imgUrl 人脸照片url
     */
    private static String faceSearch(String imgUrl,Map<String, Object> map ) {

        AipFace client = BaiduClient.getBaiduClient();
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<>(10);
        options.put("quality_control", "NORMAL");
        options.put("liveness_control", "LOW");
        options.put("max_user_num", "1");
        //查到相似度90的
        options.put("match_threshold", "90");
        String imageType = "URL";
        // 人脸搜索
        JSONObject res = client.search(imgUrl, imageType, GROUP_ID, options);
        logger.info("人脸搜索res：" + res);
        String returnCode = res.get("error_code").toString();
        //成功 -照片存在 返回userId
        if (SUCCESS_CODE.equals(returnCode)) {
            JSONObject result = new JSONObject(res.get("result").toString());
            JSONArray jsonArray = new JSONArray(result.get("user_list").toString());
            JSONObject arrayJson = new JSONObject(jsonArray.get(0).toString());
            String userId = arrayJson.get("user_id").toString();
            //匹配成功 追加
            return addUser(imgUrl, userId,map);

        } else if (USER_NOT_MATCHED_CODE.equals(returnCode)) {
            //未匹配成功  添加
            return addUser(imgUrl, null,map);
        }else {
            map.put("code", "99");
            map.put("msg", "人脸识别失败");
        }
        return "";

    }


    /**
     * 添加或者追加照片
     *
     * @param imgUrl 人脸照片
     * @param userId 百度照片库的userId
     */
    private static String addUser(String imgUrl, String userId,Map<String,Object> map) {
        AipFace client = BaiduClient.getBaiduClient();
        HashMap<String, String> options = new HashMap<>(10);
        options.put("quality_control", "NORMAL");
        options.put("liveness_control", "LOW");
        options.put("action_type", "APPEND");
        String imageType = "URL";
        if (Utils.isNull(userId)) {
            userId = Constance.getStringRandom(8);
        }
        JSONObject res = client.addUser(imgUrl, imageType, GROUP_ID, userId, options);
        logger.info("人脸添加res：" + res);
        String returnCode = res.get("error_code").toString();
        //成功 -照片存在 返回userId
        if (SUCCESS_CODE.equals(returnCode)) {
            return userId;
        } else if (FACE_ALREADY_EXIST_CODE.equals(returnCode)){
            //人脸识别已存在 当成人脸识别通过
            map.put("msg", "人脸识别通过");
            return userId;
        }else {
            map.put("code", "99");
            map.put("msg", "人脸识别失败");
            logger.info("人脸添加——失败——：" + res);
        }
        return "";
    }


    public static void main(String[] args) {

        Map<String, Object> faceApiIdentify =
                isFaceApiIdentify("http://218.78.49.18:6010/synthetical/1602757344192.jpg");
        System.out.println(faceApiIdentify.get("code"));
        System.out.println(faceApiIdentify.get("msg"));

        // 初始化一个AipFace
        AipFace client = new AipFace(BD_FACE_APP_ID, BD_FACE_API_KEY, BD_FACE_SECRET_KEY);

        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);

        // 可选：设置代理服务器地址, http和socket二选一，或者均不设置
        //        client.setHttpProxy("proxy_host", proxy_port);  // 设置http代理
        //        client.setSocketProxy("proxy_host", proxy_port);  // 设置socket代理

        //        // 调用接口
        //        String image = OpenUtils.encodeImageToBase64(new URL("http://test.caifushequ.xyz/wechatChangzheng//yjsp/1600586368318.jpg"));
        //        String imageType = "BASE64";
        //
        //        HashMap<String, String> options = new HashMap<String, String>();
        ////        options.put("face_field", "age");
        ////        options.put("max_face_num", "2");
        //        options.put("face_type", "LIVE");
        //        options.put("liveness_control", "LOW");
        //        // 人脸检测
        //        JSONObject res = client.detect(image, imageType, options);
        ////        System.out.println(res.toString(2));
        //		//getFaceToken("testCzRefrigerZhuHongFang");
        ////		Map<String,String> retMap = searchFaceRetUserId( null, "http://140.207.2.182:6008/BranchManage/img/dongtantan.jpg");
        ////		JSONObject json = new JSONObject(retMap);
        ////		System.out.println(json.toString(2));
        //
        //		//Map<String,String> retMap = searchFace(null, "https://image.baidu.com/search/detail?ct=503316480&z=undefined&tn=baiduimagedetail&ipn=d&word=%E4%BA%BA%E8%84%B8&step_word=&ie=utf-8&in=&cl=2&lm=-1&st=undefined&hd=undefined&latest=undefined&copyright=undefined&cs=1000633109,397782849&os=4044723806,1474006289&simid=4211832402,612238432&pn=1&rn=1&di=42240&ln=1480&fr=&fmq=1599123843117_R&fm=&ic=undefined&s=undefined&se=&sme=&tab=0&width=undefined&height=undefined&face=undefined&is=0,0&istype=0&ist=&jit=&bdtype=0&spn=0&pi=0&gsm=0&hs=2&objurl=http%3A%2F%2Fnwzimg.wezhan.cn%2Fcontents%2Fsitefiles2022%2F10111675%2Fimages%2F9296390.jpg&rpstart=0&rpnum=0&adpicid=0&force=undefined");
        //
        //		System.out.println(res.toString(2));
        //		System.out.println(res.get("error_code"));


        //        // 传入可选参数调用接口
        //        HashMap<String, String> options = new HashMap<String, String>();
        //        options.put("quality_control", "NORMAL");
        //        options.put("liveness_control", "LOW");
        //        options.put("match_threshold", "90");
        //        options.put("max_user_num", "1");
        //
        //        String image = OpenUtils.encodeImageToBase64(new URL("http://test.caifushequ.xyz/wechatChangzheng//childPickUp/1600679266514.jpg"));
        //        String imageType = "BASE64";
        //
        //        // 人脸搜索
        //        JSONObject res = client.search(image, imageType, GROUP_ID, options);
        //        System.out.println(res.toString(2));
        //
        //        String code = res.get("error_code").toString();
        //        if (SUCCESS_CODE.equals(code)) {
        //            JSONObject result = new JSONObject(res.get("result").toString());
        //            System.out.println(result);
        //            System.out.println("/*/*/*/*/*/*/*/*/*/*/*/*/*/*");
        //
        //            System.out.println(res.get("result"));
        //
        //            System.out.println("/*/*/*/*/*/*/*/*/*/*/*/*/*/*");
        //
        //            JSONArray jsonArray = new JSONArray(result.get("user_list").toString());
        //            System.out.println(result.get("user_list"));
        //
        //            System.out.println(jsonArray.get(0));
        //
        //            JSONObject result2 = new JSONObject(jsonArray.get(0).toString());
        //
        //            System.out.println("userId=" + result2.get("user_id").toString());
        //        } else if (USER_NOT_MATCHED_CODE.equals(code)) {
        //            //为匹配到用户  添加
        //            System.out.println("123");
        //        } else {
        //
        //        }


        //        // 传入可选参数调用接口
        //        HashMap<String, String> options = new HashMap<String, String>();
        //        options.put("quality_control", "NORMAL");
        //        options.put("liveness_control", "LOW");
        //        options.put("action_type", "APPEND");
        //        String image = OpenUtils.encodeImageToBase64(new URL("http://test.caifushequ.xyz/wechatChangzheng/childPickUp/1600678949498.jpg"));
        //        String imageType = "BASE64";
        //        String userId = "test1";
        //
        //        // 人脸注册
        //        JSONObject res = client.addUser(image, imageType, GROUP_ID, userId, options);
        //        System.out.println(res.toString(2));


    }

    //    private String getJson() {
    //        String a = "{\n" +
    //                "  \"result\": {\n" +
    //                "    \"face_token\": \"472281e57b7c2657c78a3344579ccf73\",\n" +
    //                "    \"user_list\": [{\n" +
    //                "      \"score\": 94.498161315918,\n" +
    //                "      \"group_id\": \"wh_123\",\n" +
    //                "      \"user_id\": \"1111\",\n" +
    //                "      \"user_info\": \"\"\n" +
    //                "    }]\n" +
    //                "  },\n" +
    //                "  \"log_id\": 7945894515842,\n" +
    //                "  \"error_msg\": \"SUCCESS\",\n" +
    //                "  \"cached\": 0,\n" +
    //                "  \"error_code\": 0,\n" +
    //                "  \"timestamp\": 1600831588\n" +
    //                "}";
    //        return a;
    //    }

}
